// ============================================================================
// FileName: UserRegistration.cs
//
// Description:
// Represents a user registration for a 3rd party SIP Registrar. UserRegistration objects are used by the
// SIPRegistrationAgent to manage 3rd party registrations for sipswitch users.
//
// Author(s):
// Aaron Clauson
//
// History:
// 17 May 2008	Aaron Clauson	Refactored from SIPRegistrationAgent.
//
// License: 
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) Aaron Clauson (aaronc@blueface.ie), Blue Face Ltd, Dublin, Ireland (www.blueface.ie)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that 
// the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following 
// disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Blue Face Ltd. 
// nor the names of its contributors may be used to endorse or promote products derived from this software without specific 
// prior written permission. 
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, 
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
// POSSIBILITY OF SUCH DAMAGE.
// ============================================================================

using System;
using System.Collections.Generic;
using System.Data;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
using BlueFace.VoIP.Authentication;
using BlueFace.VoIP.Net;
using BlueFace.VoIP.Net.SIP;
using BlueFace.VoIP.SIPServerCores.StatefulProxy;
using BlueFace.Sys;
using BlueFace.Sys.Net;
using Heijden.DNS;
using log4net;

#if UNITTEST
using NUnit.Framework;
#endif

namespace BlueFace.VoIP.SIPServer
{
    /// <note>
    /// From RFC3261 regarding the use of the Call-ID in REGISTER requests (pg 57 section 10.2).
    /// 
    ///       "Call-ID: All registrations from a UAC SHOULD use the same Call-ID
    ///       header field value for registrations sent to a particular
    ///       registrar.
    ///
    ///       If the same client were to use different Call-ID values, a
    ///       registrar could not detect whether a delayed REGISTER request
    ///       might have arrived out of order."
    /// </note>
    [DataContract]
    public class UserRegistration
    {
        public const int DEFAULT_REGISTRATION_EXPIRY = 3600;
        public const int MAXIMUM_ALLOWED_EXPIRY = 3600;
        public const int MINIMUM_ALLOWED_EXPIRY = 60;
        public const int OVERDUE_GRACEPERIOD_EXPIRED = 10;          // The number of seconds a registration should have been updated before setting as expired.
        public const string CONTACT_ID_KEY = "switchtag";

        private static ILog logger = AppState.GetLogger("sipregagent");
        
        [DataMember]
        public Guid RegistrationId;         // This will match the SIPProviderId the registration record is created from.

        [DataMember]
        public string Owner;                // The username of the user the registration is being maintained for.

        [DataMember]
        public string Username;
        
        [DataMember]
        public string AuthUsername;
        
        [DataMember]
        public string Password;

        [DataMember]
        public string Registrar;

        [DataMember]
        public string Realm;                // The domain/realm for the REGISTER request can be different from the SIP server the request gets sent to.

        [DataMember]
        public SIPURI Contact = null;       // Contact being maintained by this registration job.

        [DataMember]
        public SIPProtocolsEnum Protocol = SIPProtocolsEnum.UDP;
        
        [DataMember]
        public List<SIPContactHeader> ContactsList = new List<SIPContactHeader>();  // List of contacts reported back from the registrar server.

        [DataMember]
        public DateTime LastRegisterTime = DateTime.MinValue;

        [DataMember]
        public bool Registered = false;

        [DataMember]
        public int ExpirySeconds = DEFAULT_REGISTRATION_EXPIRY;

        [DataMember]
        public int OriginalExpirySeconds = DEFAULT_REGISTRATION_EXPIRY;

        [DataMember]
        public string FailureMessage = "Initialising";      // Used to record why a registration failed if it does so.

        [DataMember]
        public DateTime LastRegisterAttempt;

        [DataMember]
        public DateTime NextRegistrationTime = DateTime.MinValue;   // The time at which the nest registration attempt should be sent.

        [DataMember]
        public string CustomHeaders;                    // An optional list of custom SIP headers that will be added to register request for the SIP provider.

        public IPEndPoint RegistrarIPEndPoint = null;           // The IP end point the registration agent used for the SIP Registrar.
        public IPEndPoint RegistrationAgentIPEndPoint = null;   // The IP end point the registration agent sent the request from.

        public int CSeq = 0;                            // The SIP Header CSeq used in requests to the Registrar server.
        //public string CallId;                         // The SIP Header CallId used in requests to the Registrar server.
        public bool DeleteRequired = false;             // Set to true if this registration should be removed.
        public DateTime DeleteSent = DateTime.MinValue; // If a delete is required this will be set to the time the delete request was sent. It allows the deletion to itmeout and be removed gracefully if the server does not respond.
        public int RegistrationRetryInterval = SIPRegistrationAgent.REGISTER_FAILURERETRY_INTERVAL;   // The interval that is currently being used to retry a failed registration.
        public int BucketId;
        public bool Disabled = false;               // In some cases the registration agent will disable a registration and this will be set to true. An example is if a 403 Forbidden response is received.
        public bool RegisterInProgress = false;
        public SIPContactRegistrationEnum ContactRegisterType;
        public int NonceCount = 1;                      // When a WWW-Authenticate header is received a cnonce needs to be sent, this value incremenst each time a new cnonce is generated.

        public static Int64 Created;
        public static Int64 Destroyed;

        /*public UserRegistration(
            Guid registrationId,
            Guid providerId,
            string owner,
            string username,
            string authusername,
            string password,
            string registrar,
            string realm,
            SIPURI contact,
            int expiry)
        {
            RegistrationId = registrationId;
            ProviderId = providerId;
            Owner = owner;
            Username = username;
            AuthUsername = authusername;
            Password = password;
            Registrar = registrar;
            Realm = realm;
            ExpirySeconds = expiry;
            OriginalExpirySeconds = ExpirySeconds;

            //if (!Object.Equals(contact, null))
            if(contact != null)               
            {
               contact.Parameters.Set(CONTACT_ID_KEY, Crypto.GetRandomInt(6).ToString());
               Contact = contact;
            }
        }*/

        public UserRegistration(SIPProvider provider)
        {
            Created++;

            try
            {
                RegistrationId = provider.ProviderId;
                Owner = provider.Owner;
                Username = provider.ProviderUsername;
                AuthUsername = (provider.RegisterAuthUsername != null && provider.RegisterAuthUsername.Trim().Length > 0) ? provider.RegisterAuthUsername : Username;
                Password = provider.ProviderPassword;
                Registrar = (provider.RegisterServer != null && provider.RegisterServer.Trim().Length > 0) ? provider.RegisterServer : provider.ProviderServer;
                Realm = (provider.RegisterRealm != null && provider.RegisterRealm.Trim().Length > 0) ? provider.RegisterRealm : provider.ProviderServer;
                ExpirySeconds = provider.RegisterExpiry;
                OriginalExpirySeconds = ExpirySeconds;
                Contact = SIPURI.ParseSIPURI(provider.RegisterContact);
                if(Contact != null) 
                {
                    Contact.Parameters.Set(CONTACT_ID_KEY, Crypto.GetRandomString(6));
                }
                else
                {
                    throw new ApplicationException("UserRegistration (SIPProvider ctor) could not parse registration Contact from " + provider.RegisterContact + ".");
                }
                CustomHeaders = provider.CustomHeaders;
            }
            catch (Exception excp)
            {
                logger.Error("Exception UserRegistration (SIPProvider ctor). " + excp.Message);
                throw excp;
            }
        }

        public string ToXML()
        {
            string nextRegister = null;

            if (LastRegisterTime != DateTime.MinValue)
            {
                if (DateTime.Now.Subtract(LastRegisterTime).TotalSeconds > Int32.MaxValue || DateTime.Now.Subtract(LastRegisterTime).TotalSeconds < Int32.MinValue)
                {
                    nextRegister = "error";
                }
                else
                {
                    int secondsSinceLastRegister = Convert.ToInt32(DateTime.Now.Subtract(LastRegisterTime).TotalSeconds);

                    if (ExpirySeconds - secondsSinceLastRegister <= 0 && ExpirySeconds - secondsSinceLastRegister + OVERDUE_GRACEPERIOD_EXPIRED >= 0)
                    {
                        nextRegister = "re-registering";
                    }
                    else
                    {
                        double nextRegisterSec = ExpirySeconds - secondsSinceLastRegister;
                        nextRegister = (nextRegisterSec <= 0) ? "expired" : nextRegisterSec.ToString() + "s";
                    }
                }
            }

            string lastRegisterAttemptStr = (LastRegisterAttempt != DateTime.MinValue) ? LastRegisterAttempt.ToString("dd MMM yyyy HH:mm:ss") : "never";
            double nextRegisterAttempt = MAXIMUM_ALLOWED_EXPIRY;
            if (NextRegistrationTime.Subtract(DateTime.Now).TotalSeconds < Int32.MaxValue && NextRegistrationTime.Subtract(DateTime.Now).TotalSeconds > Int32.MinValue)
            {
                nextRegisterAttempt = Convert.ToInt32(NextRegistrationTime.Subtract(DateTime.Now).TotalSeconds);
            }
            string nextRegAttemptStr = (nextRegisterAttempt <= 0) ? "registering" : nextRegisterAttempt.ToString("0") + "s";

            string regXML =
               "<registration>" +
               " <registrationid>" + RegistrationId + "</registrationid>" +
               " <owner>" + Owner + "</owner>" +
               " <registered>" + Registered + "</registered>" +
               " <regusername>" + Username + "</regusername>" +
               " <regauthusername>" + AuthUsername + "</regauthusername>" +
               " <regpassword>" + Password + "</regpassword>" +
               " <registrar>" + Registrar + "</registrar>" +
               " <realm>" + Realm + "</realm>" +
               " <expiry>" + OriginalExpirySeconds + "</expiry>" +
               " <contact>" + SafeXML.MakeSafeXML(Contact.ToString()) + "</contact>" +
               " <failuremessage>" + SafeXML.MakeSafeXML(FailureMessage) + "</failuremessage>" +
               " <lastregisterattempt>" + lastRegisterAttemptStr + "</lastregisterattempt>" +
               " <nextregisterattempt>" + nextRegAttemptStr + "</nextregisterattempt>" + 
               " <contactslist>";

            if (ContactsList != null && ContactsList.Count > 0)
            {
                foreach (SIPContactHeader contactHeader in ContactsList)
                {
                    if (contactHeader.ContactURI.Parameters.Get(CONTACT_ID_KEY) == Contact.Parameters.Get(CONTACT_ID_KEY))
                    {
                        regXML += "<contact owner='true'>";
                        regXML += "<contacturi>" + contactHeader.ContactURI.ToString() + "</contacturi>";
                        regXML += "<expires>" + nextRegister + "</expires>";
                        regXML += "<lastregistertime>" + LastRegisterTime.ToString("dd MMM yyyy HH:mm:ss") + "</lastregistertime>";
                        regXML += "</contact>";
                    }
                    else
                    {
                        regXML += "<contact>" + " <contacturi>" + contactHeader.ContactURI.ToString() + "</contacturi>";

                        if (contactHeader.Expires <= 0)
                        {
                            regXML += "<expires>expired</expires>";
                        }
                        else
                        {
                            regXML += "<expires>" + contactHeader.Expires + "</expires>";
                        }

                        regXML += "</contact>";
                    }
                }
            }

            regXML +=
            " </contactslist>" +
            "</registration>";

            //logger.Debug(regXML);

            return regXML;
        }

        ~UserRegistration()
        {
            Destroyed++;
        }

        #region Unit testing.

        #if UNITTEST

        [TestFixture]
        public class UserRegistrationUnitTest
        {
            [TestFixtureSetUp]
            public void Init()
            { }

            [TestFixtureTearDown]
            public void Dispose()
            { }

            [Test]
            public void SampleTest()
            {
                Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

                Assert.IsTrue(true, "True was false.");

                Console.WriteLine("---------------------------------");
            }

            [Test]
            [ExpectedException(typeof(ApplicationException))]
            public void CreateUserRegistrationNullContactUnitTest()
            {
                SIPProvider sipProvider = new SIPProvider("owner", "provider", "username", "password", "server.com", null, null, null, null, 3600, null, null, null, false, false);
                UserRegistration userReg = new UserRegistration(sipProvider);
            }

            [Test]
            public void CreateUserRegistrationValidContactUnitTest()
            {
                DateTime startTime = DateTime.Now;
                SIPURI contactURI = SIPURI.ParseSIPURI("sip:test@test.com");
                Console.WriteLine("Parse SIP URI time = " + DateTime.Now.Subtract(startTime).TotalMilliseconds + " ms.");

                SIPProvider sipProvider = new SIPProvider("owner", "provider", "username", "password", "server.com", null, null, null, contactURI.ToString(), 3600, null, null, null, false, false);
                UserRegistration userReg = new UserRegistration(sipProvider);

                Assert.IsNotNull(userReg.Contact, "Contact should not have been null.");
            }
        }

        #endif

        #endregion
    }
}
